//
//  DataCache.m
//  10.13
//
//  Created by M on 16/11/16.
//  Copyright © 2016年 apple1512. All rights reserved.
//

#import "DataCache.h"

@implementation DataCache
+ (void)loginWithName:(NSString *)name password:(NSString *)password complete:(void (^)(NSDictionary *))handle
{
    NSDictionary *param = @{
                            @"name":name,
                            @"password":password
                            };
    [self getDataWithParam:param urlString:@"http://xl18z.cn/login.php" complete:^(NSDictionary *data) {
        handle(data);
    }];
}

+ (void)getUserListAtPage:(int)page complete:(void (^)(NSDictionary *))handle
{
    NSDictionary *param = @{
                            @"page":@(page)
                            };
    [self getDataWithParam:param urlString:@"http://xl18z.cn/list.php" complete:^(NSDictionary *data) {
        handle(data);
    }];
}

+ (void)getDataWithParam:(NSDictionary *)param urlString:(NSString *)urlString complete:(void (^)(NSDictionary *data))handle
{
    
    NSMutableString *str = [[NSMutableString alloc] initWithString:urlString];
    [str appendString:@"?"];
    for(NSString *key in param){
        [str appendFormat:@"%@=%@&",key,param[key]];
    }
    NSString *str2 = [str substringToIndex:str.length - 1];
    NSURL *url = [NSURL URLWithString:str2];
    
    NSURLRequest *req = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        dispatch_async(dispatch_get_main_queue(), ^{
            handle(dict);
        });
        
    }];
    [task resume];
}
@end
